package cc.mrbird.febs.api;

import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.customer.entity.Activity;
import cc.mrbird.febs.customer.entity.Customer;
import cc.mrbird.febs.customer.entity.Order;
import cc.mrbird.febs.customer.service.IActivityService;
import cc.mrbird.febs.customer.service.ICustomerService;
import cc.mrbird.febs.customer.service.IOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;

/**
 * @ Author 马超伟
 * @ Date 2020-11-04 14:58
 * @ Description:
 * @ Version: 活动表接口
 */
@RestController
@RequestMapping("/api/activity")
public class ActivityApiController extends BaseController {

    @Resource
    private IActivityService activityService;

    @Resource
    private IOrderService orderService;

    @Resource
    private ICustomerService customerService;

    /**
     * @ Author: 马超伟
     * @ Date: 2020/11/4 15:02
     * @ Params: []
     * @ return: cc.mrbird.febs.common.entity.FebsResponse
     * @ Description: 获取活动接口
     */
    @RequestMapping(value = "/getActivity",method = RequestMethod.GET)
    public FebsResponse getActivity(String activityId){
        if (StringUtils.isBlank(activityId)){
            return new FebsResponse().fail().message("activityId为空！");
        }
        Activity activity = activityService.getOne(new QueryWrapper<Activity>().lambda().eq(Activity::getTActivityId,activityId));
        if (activity==null){
            return new FebsResponse().fail().message("activityId为空！");
        }
        activity.setVisitNum(activity.getVisitNum()+1);
        activityService.updateById(activity);

        FebsResponse response = new FebsResponse().success();
        response.put("activity",activity);

        //TODO 添加订单表数据，比如最近购买人数等
        List<Order> orderList = orderService.list(new QueryWrapper<Order>().lambda()
                .select(Order::getOpenId)
                .eq(Order::getBody, activity.getName())
                .eq(Order::getIsSuccess,1));
        //查询已购买人数
        response.put("total_order",orderList.size());

        double progress = (double)orderList.size()/(double)activity.getLimitNumber()*100.0;
        //进度百分比
        response.put("progress", String.format("%.2f", progress));

        List<Customer> customers = new ArrayList<>();
        for (Order order : orderList) {
            Customer customer = customerService.getOne(new QueryWrapper<Customer>().lambda()
                    .select(Customer::getNickname,Customer::getHeadimgurl)
                    .eq(Customer::getOpenid,order.getOpenId()));
            if (customer.getNickname().length()>3){
                customer.setNickname(customer.getNickname().substring(0,2)+"...");
            }
            customers.add(customer);
        }
        //查询购买用户列表
        response.put("customer_pay_list",customers);

        //遍历下订单中，pid不为0 的客户，
        customers.stream().filter(s->s.getPid()!=0);
        Map<Customer, Integer> customerIntegerMap = countList(customers);
        Set<Customer> customerSet = customerIntegerMap.keySet();
        //TODO 先这样计算着，回头整整理
        for (Customer customer : customerSet) {
            Integer integer = customerIntegerMap.get(customer);
            customer.setPrice(activity.getPrice().multiply(new BigDecimal(integer)));
        }
        //查询推广人收益表
        List customerIntegerMapList = mapTransitionList(customerIntegerMap);
        response.put("bonus_list",customerIntegerMapList);
        return response;
    }

    /**
     * @ Author: 马超伟
     * @ Date: 2020/11/4 16:23
     * @ Params: [reslist]
     * @ return: java.util.Map<cc.mrbird.febs.customer.entity.Customer,java.lang.Integer>
     * @ Description: 统计元素出现次数
     */
    private Map<Customer,Integer> countList(List<Customer> reslist){
        Map<Customer,Integer> countmap = new HashMap<>();
        for(int i=0; i<reslist.size(); i++){
            //在Map中查找关键字，如果没有就put进Map中，同时value值加1
            if(null==countmap.get(reslist.get(i))){
                countmap.put(reslist.get(i), 1);
            }else{ //如果有Map中有该元素，说明已经put过了，则直接value值计数加1
                countmap.put(reslist.get(i), countmap.get(reslist.get(i))+1);
            }
        }
        return countmap;
    }


    // map转换成list
    public static List mapTransitionList(Map map) {
        List list = new ArrayList();
        Iterator iter = map.entrySet().iterator(); // 获得map的Iterator
        while (iter.hasNext()) {
            Entry entry = (Entry) iter.next();
            Customer customer = (Customer) entry.getKey();
            customer.setBonusNumber((Integer)entry.getValue());
            list.add(customer);
        }
        return list;
    }

}
